package com.tgb.lk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author vma
 */
public class ManageClassLoader {
	DynamicClassLoader dc = null;

	Long lastModified = 0L;
	Class<?> c = null;

	// 加载类， 如果是文件夹则加载本文件夹中的所有class,如果是class则加载本class.
	public List<Class<?>> loadClass(String path) throws ClassNotFoundException,
			IOException {
		dc = new DynamicClassLoader();
		File baseFile = new File(path);
		List<Class<?>> classes = new ArrayList<Class<?>>();
		Class<?> c = null;
		if (baseFile.isDirectory()) {
			File[] files = baseFile.listFiles();
			for (File file : files) {
				if (file.isFile() && file.getName().endsWith(".class")) {
					c = dc.findClass(getBytes(file.getPath()));
					classes.add(c);
				}
			}
		} else if (baseFile.isFile() && baseFile.getName().endsWith(".class")) {
			c = dc.findClass(getBytes(path));
			classes.add(c);
		}

		return classes;
	}

	// 判断是否被修改过
	public boolean isClassModified(String filename) {
		boolean returnValue = false;
		File file = new File(filename);
		if (file.lastModified() > lastModified) {
			returnValue = true;
		}
		return returnValue;
	}

	// 从本地读取文件
	private byte[] getBytes(String filename) throws IOException {
		File file = new File(filename);
		long len = file.length();
		lastModified = file.lastModified();
		byte raw[] = new byte[(int) len];
		FileInputStream fin = new FileInputStream(file);
		int r = fin.read(raw);
		if (r != len) {
			throw new IOException("Can't read all, " + r + " != " + len);
		}
		fin.close();
		return raw;
	}
}
